import request from 'wxapp-request';
import { isString } from 'lodash';
import env from '../env';
import { uploadFile } from './wxApis';

class UploadError extends Error {
  constructor(message, detail) {
    super(message);
    this.name = 'UploadError';
    this.detail = detail;
  }
}

function getSuffix(filePath) {
  const suffix = filePath.split('.').pop();
  if (!suffix) {
    throw new Error(`filePath ${filePath} 不含有正确的后缀`);
  }
  return suffix;
}

function getName(filePath) {
  const a = filePath.split('/').pop().split('.');
  console.log(a);
  a.pop();
  const suffix = a.join('.');

  console.log(suffix);
  if (!suffix) {
    throw new Error(`filePath ${filePath} 不含有正确的后缀`);
  }
  return suffix;
}

async function getAuthorization(filePath) {
  const { code, data, message } = await request.get(`${env.API_URL}/sign/ma/cos/get_one_effective_sign`, {
    data: {
      blessId: getName(filePath),
      productType: 1001,
      suffix: getSuffix(filePath),
    },
  });
  if (code === 1) {
    return data;
  }
  throw new Error(message || '获取失败鉴权信息');
}


/**
 * 上传方法
 * filePath: 上传的文件路径
 * fileName： 上传到cos后的文件名
 */
async function upload(filePath) {
  const { url, sign } = await getAuthorization(filePath);
  const res = await uploadFile({
    url,
    filePath,
    header: { Authorization: sign },
    name: 'filecontent',
    formData: { op: 'upload' },
  });
  const result = isString(res.data) ? JSON.parse(res.data) : res.data;
  if (result.message !== 'SUCCESS') {
    throw new UploadError(result.message, result);
  }
  return result;
}

export default upload;
